package com.ostrich.lib_common.net;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;

import androidx.lifecycle.LiveData;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/6 08:17
 * @Description : LiveDataCallAdapter
 */
public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<R>> {
    public LiveDataCallAdapter(Type observableType) {
        this.observableType = observableType;
    }

    private Type observableType;

    @Override
    public Type responseType() {
        return observableType;
    }

    @Override
    public LiveData<R> adapt(Call<R> call) {
        return new LiveData<R>() {
            AtomicBoolean start = new AtomicBoolean(false);
            @Override
            protected void onActive() {
                super.onActive();
                if (start.compareAndSet(false, true)){
                    call.enqueue(new Callback<R>() {
                        @Override
                        public void onResponse(Call<R> call, Response<R> response) {
                            if(response.code() == 200){
                                postValue(response.body());
                            }else{
                                postValue((R) new BaseResponseEntity(response.code(),response.message()));
                            }
                        }

                        @Override
                        public void onFailure(Call<R> call, Throwable t) {
                            postValue((R) new BaseResponseEntity(404,t.getMessage()));

                        }
                    });
                }

            }
        };
    }
}
